//
//  ViewController.m
//  20504
//
//  Created by student on 16/3/23.
//  Copyright © 2016年 NIIT. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
@property(assign,nonatomic) int tickets;
@property(strong,nonatomic) NSLock *lock;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.lock=[[NSLock alloc]init];
    self.tickets=100;
    NSThread *thread1=[[NSThread alloc]initWithTarget:self selector:@selector(cell2) object:nil];
    thread1.name=@"TFboys(王源)";
    NSThread *thread2=[[NSThread alloc]initWithTarget:self selector:@selector(cell2) object:nil];
    thread2.name=@"TFboys(王俊凯)";
    NSThread *thread3=[[NSThread alloc]initWithTarget:self selector:@selector(cell2) object:nil];
    thread3.name=@"TFboys(易烊千玺)";
    [thread1 start];
    [thread2 start];
    [thread3 start];
}

-(void)cell
{
    while(1)
    {
        NSDate *d1=[NSDate date];
        @synchronized(self)
        {
            NSLog(@"%@:准备卖票",[NSThread currentThread].name);
            NSDate *d2=[NSDate date];
            NSTimeInterval t= [d2 timeIntervalSinceDate:d1];
            NSLog(@"%@:等待了:%.3f秒",[NSThread currentThread].name,t);
            int count=self.tickets;
            if(count>0)
            {
                [NSThread sleepForTimeInterval:0.03];
                self.tickets-=1;
                NSLog(@"%@:卖出一张票剩余%i",[NSThread currentThread].name,self.tickets);
                
            }
            else
            {
                NSLog(@"票卖光了");
                [NSThread exit];
            }
        }
    }
}
-(void)cell2
{
    while(1)
    {
        if([self.lock tryLock])
        {
            int count=self.tickets;
            if(count>0)
            {
                [NSThread sleepForTimeInterval:0.03];
                self.tickets=self.tickets-1;
                [self.lock unlock];
                NSLog(@"%@:卖出一张票剩余%i",[NSThread currentThread].name,self.tickets);
                NSLog(@"%@:吃口翔休息下!",[NSThread currentThread].name);
                [NSThread sleepForTimeInterval:0.01];
            }
            else
            {
                NSLog(@"票卖光了");
                [self.lock unlock];
                [NSThread exit];
            }

        }
        else
        {
            NSLog(@"%@：有人在卖票在下先看会报纸",[NSThread currentThread].name);
            [NSThread sleepForTimeInterval:0.01];
        }
    }

}

@end
